goog.provide('dkpoints.raid.uploadview');

goog.require('goog.dom');
goog.require('goog.events');

goog.require('dkpoints.raid');
goog.require('dkpoints.raid.parser');
goog.require('dkpoints.raid.templates');

/**
 * Build the Upload UI
 * @param {function({object})} callback to call when raid is successfully parsed.
 */
dkpoints.raid.uploadview.loadUI = function(callback) {
  var me = dkpoints.raid.uploadview;
  var raidAPI = dkpoints.raid;
  
  // Save the callback
  me.callback = callback;

  // Render the Upload UI.
  var body = goog.dom.$('body_content');
  body.innerHTML = raidAPI.templates.uploadNew(null, null);
  
  // Set up event handling for the Verify button.
  var verifyButton = goog.dom.$('btnImport');
  goog.events.listen(verifyButton, goog.events.EventType.CLICK, me.verify, false, me);
};

/**
 * Verify button was clicked.  Parse the raid XML string and pop the callback.
 * @param {Object} event The click event.
 */
dkpoints.raid.uploadview.verify = function(event) {
  var me = dkpoints.raid.uploadview;
  
  // Get the text from the textarea and check if it's an XML string
  var raidString = goog.dom.$('ImportXML').value;
  if(raidString.substring(0, 5) == "<raid") {
    // Yep, it's XML.  Send to parser.
    var newRaid = dkpoints.raid.parser.buildFromHeadcount(raidString);
    me.callback(newRaid);
  }
  else if(raidString.length > 0) { // non-empty list of players
    var newRaid = dkpoints.raid.parser.buildFromPlayerList(raidString);
    me.callback(newRaid);
  }
  else { // Completely empty.  Build the raid from scratch in ParsedView.
    var newRaid = new dkpoints.raid.Raid();
    newRaid["info"]["_parseOrigin"] = "Empty";
    
    me.callback(newRaid);
  }
};

dkpoints.raid.uploadview.teardown = function() {
  var me = dkpoints.raid.uploadview;
  
  // Tear down event listeners.
  var verifyButton = goog.dom.$('btnImport');
  goog.events.unlisten(verifyButton, goog.events.EventType.CLICK, me.verify, false, me);
  
  // Destroy references.
  delete me.callback;
  
  // Clear DOM.
  goog.dom.$('body_content').innerHTML = "";
};